package cn.lystudio.rohm_time_op.exceptions;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.util.SaResult;
import cn.lystudio.rohm_time_op.entity.vo.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 未登录异常处理器
     * @param exception
     * @return
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseBody
    public SaResult notLoginExeceptionHandler(NotLoginException exception){
        log.error("NOT LOGIN : {}",exception.getMessage() );
        return SaResult.error(exception.getMessage());
    }

    /**
     * 数据库重复值异常
     * @param exception
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    @ResponseBody
    public SaResult duplicateKeyException(DuplicateKeyException exception){
        log.error("数据库唯一值约束: {},{}",exception.getClass(),exception.getMessage());
        return SaResult.error("数据库有重复值");
    }

    /**
     * 自定义异常处理器
     * 使用例: throw new JsonException(Status.UNKNOWN_ERROR);
     * @param exception
     * @return
     */
    @ExceptionHandler(value = JsonException.class)
    @ResponseBody
    public ApiResponse jsonErrorHandler(JsonException exception) {
        log.error("【JsonException】:{}", exception.getMessage());
        //return ApiResponse.ofException(exception);
        return ApiResponse.ofException(exception);
    }

    /**
     * 找不到下载apk文件异常
     * @param exception
     * @return
     */
    @ExceptionHandler(DownloadAppException.class)
    @ResponseBody
    public SaResult downloadAppExceptionHandler(DownloadAppException exception){
        log.error("APK EXCEPTION: {}",exception.getMessage());
        return SaResult.error(exception.getMessage());
    }

    /**
     * 通用异常处理器
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public SaResult commonExceptionHandler(Exception exception){
        log.error("COMMON EXCEPTION: {},{}",exception.getClass(),exception.getMessage());
        return SaResult.error(exception.getMessage());
    }
}
